var dataGrid;
$(function(){
	dataGrid = $('#dataGrid').datagrid({
		title:'角色列表',
		iconCls:'icon-tip',
		nowrap: false,
		striped: true,
		queryParams:{}, //查询条件  
		url: contextPath + '/role/getRoleListData.action',
		sortName: 'id',
		sortOrder: 'asc',
		loadMsg:'数据加载中请稍后...', 
		remoteSort: false,
		idField:'id',
		fitColumns:true,
		/*singleSelect: true,*/
		pagination:true,
        rownumbers:true,
        scrollbarSize:0,
		columns:[[
            {field:'ck',checkbox:true},
            {title:'编号',field:'id',width:35,sortable:true,
            	sorter:function(a,b){
					return (a>b?1:-1);
				}
            },
			{title:'名称',field:'name',width:100,sortable:true},
			{title:'描述',field:'description',width:150,sortable:true},
			{field:'opt',title:'操作',width:100,align:'center',
				formatter:function(value,rowData){
					var roleId = rowData.id;
					var optTemplate =  "<a class=\"btn btn-mini ml5\" href=\"javascript:privilegeForRole('"+roleId+"');\"><i class=\"icon-cog\"></i>分配权限</a>";
						optTemplate += "<a class=\"btn btn-mini ml5\" href=\"javascript:editRole('"+roleId+"');\"><i class=\"icon-edit-data\"></i>修改</a>";
					    optTemplate += "<a class=\"btn btn-mini ml5\" href=\"javascript:delRole('"+roleId+"');\"><i class=\"icon-remove-data\"></i>删除</a>";
					return optTemplate;
				}
			}
		]],
		onLoadSuccess:function(){ 
			//一定要加上这一句，要不然datagrid会记住之前的选择状态，删除时会出问题
			$('#dataGrid').datagrid('clearSelections');
		}  
	});
	
	$('#searchPanel').panel({  
		width:"100%",  
		height:"100%", 
		/*collapsible:true,*/
		title: '角色查询'
	});  
	
    // 当窗口大小发生变化时，调整DataGrid的大小  
    $(window).resize(function() { 
    	$('#searchPanel').panel('resize',{width:$(document.body).width() - 10});
        $('#dataGrid').resizeDataGrid(300);  
    });  
    
    //查询操作
    $("#queryBtn").click(function(){
        var queryForm = $("#queryForm").serializeArray();
		var queryParams = $('#dataGrid').datagrid('options').queryParams;
        $.each(queryForm, function(i, field){
            queryParams[field.name] = field.value;
        });
        //重新加载datagrid的数据  
        $("#dataGrid").datagrid('load');
    });
    
    //添加
    $("#add-role-btn").click(function(){
    	$('#dataGrid').datagrid('clearSelections');
    	showDialog("添加角色",contextPath+"/role/toAddRole.action");
    });
    
    //删除
    $("#delete-role-btn").click(function(){
    	var ids = [];
		var rows = $('#dataGrid').datagrid('getSelections');
		if (rows.length == 0) {
        	$.messager.alert('提示', '请选择要删除的记录!', 'info');
        	return;
    	}
    	for (var i = 0; i < rows.length; i++) {
        	ids.push(rows[i].id);
    	}
    	delRole(ids);
	});
    
});

function showDialog(title,url){
	parent.$.modalDialog({
		title : title,
		iconCls:"icon-tip",
		width:600,
		height:325,
		href : url,
		buttons:[{ 
			text : '确定',
			iconCls : 'icon-ok',
			handler : function() {
				parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
				var f = parent.$.modalDialog.handler.find('#form');
				f.submit();
			}
		}, {
			text : '取消',
			iconCls : 'icon-cancel',
			handler : function() {
				parent.$.modalDialog.handler.dialog('close');
		   } 
		}]
	});
}

function editRole(roleId){
	dataGrid.datagrid('clearSelections');
	showDialog("修改角色",contextPath+"/role/toEditRole.action?id="+roleId);
}

function delRole(roleIds){
	$.messager.confirm('提示', '确定要删除吗？',function(r){
        if(r){
            $.ajax({
                url: contextPath+'/role/delRole.action',
                type: 'post',
                data: "roleIds="+roleIds,
                error: function(){
                	$.messager.alert('提示','操作失败，请重新再试！','error');      
                },
                success: function(data){
                    if (data.result == 'success') {
                        $.messager.alert('提示', '删除成功!','info');
                        $("#dataGrid").datagrid('reload');
                    }else if("10001" == data.errorCode){
                    	$.messager.alert('提示', '选择的角色中存在被用户引用不能删除。','warning');  
                    }else{
                    	$.messager.alert('提示','操作失败，请重新再试！','error');
                    }        
                }
            });
        }
    });
}
//分配权限
function privilegeForRole(roleId){
	parent.$.modalDialog({
		title : "权限分配",
		iconCls:"icon-tip",
		width:350,
		height:422,
		href : contextPath+"/role/toPrivilegeForRole.action?id="+roleId,
		buttons:[{ 
			text : '确定',
			iconCls : 'icon-ok',
			handler : function() {
				parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
				var nodes = parent.$.modalDialog.handler.find('#privilegeTree').tree('getChecked');
				//获取级联父节点
				/*parent.$.modalDialog.handler.find('#privilegeTree').find('.tree-checkbox2').each(function(){
					var node = $(this).parent();
					nodes.push($.extend({}, $.data(node[0], 'tree-node'), {
							target: node[0],
						    checked: node.find('.tree-checkbox').hasClass('tree-checkbox2')
					}));
				});*/
				var privilegeIds = '';
				for(var i=0; i<nodes.length; i++){
					if(privilegeIds != '') privilegeIds += ',';
					privilegeIds += nodes[i].id;
				}
				$.ajax({
					type : "post",
					url : contextPath + "/role/privilegeForRole.action",
					data : {
						'role.id' : roleId,
						'privilegeIds' : privilegeIds
					},
					datatype: "json",
					success : function(data) {
						parent.$.modalDialog.handler.dialog('close');
						if (data.result == 'success') {
	                        parent.$.messager.alert('提示', data.msg,'info');
	                    }else{
	                    	parent.$.messager.alert('提示', data.msg,'error');
	                    }      
					},
					error : function(){
						$.messager.alert('提示','操作失败，请重新再试！','error');  
					}
				});	
			}
		}, {
			text : '取消',
			iconCls : 'icon-cancel',
			handler : function() {
				parent.$.modalDialog.handler.dialog('close');
		   } 
		}]
	});
}